package com.bw.parkingspace_module.parking

import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.BarUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.bw.parkingspace_module.R
import com.bw.parkingspace_module.databinding.ActivityParkingBinding
import com.bw.parkingspace_module.parking.adapter.ParkingAdapter
import com.bw.parkingspace_module.parking.entity.ParkingAllEntity
import com.bw.parkingspace_module.parking.entity.ParkingValueEntity
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.google.gson.Gson
import com.kf.common.entity.EventBusEntity
import com.kf.common.entity.EventBusType
import com.kf.common.mvi.view.BaseActivity
import com.kf.lib_widget.divider.ParkingDivider
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

@Route(path = "/parking/parkingactivity")
class ParkingActivity : BaseActivity<ActivityParkingBinding, ParkingViewModel>(),
    OnItemClickListener {

    @Autowired
    lateinit var action: String

    //定义车位申请适配器
    lateinit var parkingAdapter: ParkingAdapter

    //点击可申请车位，获取到下标
    var position: Int = -1

    //可以申请车位的数量
    var unCount = 0

    override fun createViewModel(): ParkingViewModel {
        return viewModels<ParkingViewModel>().value
    }

    override fun createViewBind(): ActivityParkingBinding {
        return ActivityParkingBinding.inflate(inflater)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ARouter.getInstance().inject(this)
        BarUtils.setStatusBarColor(this, Color.parseColor("#2196F3"))
        EventBus.getDefault().register(this)
        mViewModel.requestParkingAll()
        BindParkingAll()
        initParkingRecycler()
        initClick()
    }

    private fun initClick() {
        mView.parkingBack.setOnClickListener {
            finish()
        }
    }

    //初始化recycler
    private fun initParkingRecycler() {
        mView.parkingRecycler.layoutManager = GridLayoutManager(this, 6)
        parkingAdapter = ParkingAdapter()
        parkingAdapter.setOnItemClickListener(this)
        mView.parkingRecycler.addItemDecoration(ParkingDivider(this))
        mView.parkingRecycler.adapter = parkingAdapter
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    private fun BindParkingAll() {
        lifecycleScope.launch(Dispatchers.Main) {
            mViewModel.mutableContainer.uiStateFlow.collect {
                if (it.entity!!.statuesCode == 200)
                    initRecycler(it.entity!!.values)
            }

        }
    }

    private fun initRecycler(list: List<ParkingValueEntity>?) {
        var parkArrayList: ArrayList<ParkingAllEntity> = ArrayList()
        var index = list!!.size % 5
        var line = 0
        var parkingAllEntity: ParkingAllEntity

        if (index == 0)
            line = list!!.size / 5
        else
            line = (list!!.size / 5) + 1

        var z = 0
        for (i in 0..list.size - 1 + line) {
            var j = i % 6
            parkingAllEntity = ParkingAllEntity()
            if (i % 6 == 0) {
                parkingAllEntity.type = 1
                parkingAllEntity.name = "${line}"
            } else {
                if (list.get(z).parkUser == 0) {
                    parkingAllEntity.color = Color.parseColor("#A9ED59")
                    unCount++
                } else
                    parkingAllEntity.color = Color.parseColor("#CDCECF")
                parkingAllEntity.type = 2
                parkingAllEntity.name = "1 - ${line + 1}0${j}"
                parkingAllEntity.entity = list.get(z)
                ++z
            }
            if (line > 0 && j == 0)
                --line
            parkArrayList.add(parkingAllEntity)
        }
        parkingAdapter.setNewInstance(parkArrayList)
        mView.parkingOptions.setText("可选（${unCount}）")
        mView.parkingNonoptional.setText("不可选（${list.size - unCount}）")
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        var parkingAdapters: ParkingAdapter = adapter as ParkingAdapter
        var data = parkingAdapters.data
        if (position % 6 != 0) {
            if (data.get(position).entity!!.parkUser != 0) {
                ToastUtils.showShort("该车位已有人，请选择其他车位")
                return
            } else {
                this.position = position
                if (action.equals("visitor")) {
                    var map = HashMap<String, Any>()
                    map.put("parkEntity",Gson().toJson(data.get(position).entity))
                    var eventBusEntity = EventBusEntity(EventBusType.VISITOR,map)
                    EventBus.getDefault().post(eventBusEntity)
                    finish()
                    return
                }
                ARouter.getInstance().build("/parking/parkingvractivity")
                    .withSerializable("parkingEntity", data.get(position).entity).navigation()
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun eventBus(eventBusEntity: EventBusEntity) {
        if (eventBusEntity.action == EventBusType.PARKING_SUCCESS) {
            mViewModel.requestParkingAll()
        }
    }
}